package thread.java20230110;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用ReentrantLock, 两个线程对一个数自增5w次
 */
public class Demo51 {
    static int count = 0;
    static ReentrantLock locker = new ReentrantLock();
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            try {
                locker.lock();//获取锁
                for (int i = 0;i<50000; i++){
                    count ++;
                }
            }finally {
                locker.unlock();//释放锁
            }

        });

        Thread thread2 = new Thread(()->{
            try {
                locker.lock();
                for (int i = 0;i<50000; i++){
                    count ++;
                }
            }finally {
                locker.unlock();
            }

        });

        thread.start();
        thread2.start();
        thread.join();
        thread2.join();
        System.out.println(count);
    }
}
